/**
 * 
 */
package cs534;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jhostetler
 *
 */
public class EmpiricalDistribution<T> extends Distribution<T>
{
	private final Map<T, double[]> dist_ = new HashMap<T, double[]>();
	private final int Nsamples_;
	
	public EmpiricalDistribution( final Sampler<T> sampler, final int Nsamples )
	{
		Nsamples_ = Nsamples;
		for( int i = 0; i < Nsamples; ++i ) {
			final T sample = sampler.sample();
			final double[] c = dist_.get( sample );
			if( c != null ) {
				c[0] += 1;
			}
			else {
				dist_.put( sample, new double[] { 1.0 } );
			}
		}
		final double Zinv = 1.0 / Nsamples_;
		for( Map.Entry<T, double[]> e : dist_.entrySet() ) {
			e.getValue()[0] *= Zinv;
		}
	}
	
	public Map<T, double[]> sparse_distribution()
	{
		return dist_;
	}
	
	/**
	 * @see cs534.Distribution#pdf(java.lang.Object)
	 */
	@Override
	public double pdf( final T t )
	{
		final double[] d = dist_.get( t );
		return (d != null ? d[0] : 0.0);
	}

}
